#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Bartol data format

Copyright (c) 2011-2013 Christian T. Steigies <steigies@physik.uni-kiel.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

__author__ = "Christian T. Steigies <steigies@physik.uni-kiel.de>"
__license__ = "GPL License"


## --------------------------------------------------------------------------
#import MySQLdb # python-mysqldb

#import os
import sys
import datetime
#import calendar
#from numpy import array

from nmdb.station.station_data import check_data, check_pressure
from nmdb.tools.datetool import parse_date
from nmdb.tools.pressure import mbar

#__all__ = ["", ""]

## --------------------------------------------------------------------------

bartol_station = ["mcmu", "newk", "sopo", "sopb", "thul",
                  "fsmt", "pwnk", "nain", "invk"]
bartol_longnames = {"mcmu": "McMurdo",
                    "newk": "Swarthmore/Newark",
                    "sopo": "South Pole",
                    "sopb": "South Pole Bares",
                    "thul": "Thule",
                    "fsmt": "Fort Smith",
                    "pwnk": "Peawanuck",
                    "nain": "Nain",
                    "invk": "Inuvik"}

## --------------------------------------------------------------------------
def read_rev(options, station, data_type, year, month, day):
    """read revised data

    options     verbose, dryrun, ...
    station     station short name, must be valid station
    data_type   "1m", "1h", "env", "meta"
    year        integer (1950-9999)
    month       integer (1-12)
    day         integer (1-31)

    return list of values in nmdb format
    """

    if station in bartol_station:
        extra = ""
    else:
        raise ValueError  # wrong station

    if data_type in ["1h"]:
        filename = options.datadir + "/" + station.upper() + extra + "_Hour.txt"
    elif data_type in ["1m"]:
        filename = options.datadir + "/" + station.upper() + extra + "_Minute.txt"
    elif data_type in ["env", "meta"]:
        return None
    else:
        raise ValueError  # illegal data_type

    data = read_txt(filename, data_type)  # TODO options
    value = date_filter(data, year, month, day)

    return value
## --------------------------------------------------------------------------
def read_rt(options, station, data_type, year, month, day):
    """read real-time data

    options     verbose, dryrun, ...
    station     station short name, must be valid station
    data_type   "1m", "1h", "env", "meta"
    year        integer (1950-9999)
    month       integer (1-12)
    day         integer (1-31)

    return list of values in nmdb format
    """

    if station in bartol_station:
        extra = "_QL"
    else:
        raise ValueError  # wrong station

    if data_type in ["1h"]:
        filename = options.datadir + "/" + station.upper() + extra + "_Hour.txt"
    elif data_type in ["1m"]:
        filename = options.datadir + "/" + station.upper() + extra + "_Minute.txt"
    elif data_type in ["env", "meta"]:
        return None
    else:
        raise ValueError  # illegal data_type

    data = read_txt(filename, data_type)  # TODO options
    value = date_filter(data, year, month, day)

    return value

## --------------------------------------------------------------------------
def date_filter(data, year, month, day):
    """filter data by given year, month, and day"""

    value = []
    for row in data:
        thisdate = row[0].date()
        if thisdate.year == year and thisdate.month == month and thisdate.day == day:
            value.append(row)

    return value

## --------------------------------------------------------------------------
def read_bartol(options, station, data_type, data_source, year=None, month=None, day=None):
    """read data for Bartol stations"""

    if data_source in ["revised"]:  # revised data
        extra = ""
    elif data_source in ["realtime"]:  # real-time data
        extra = "_QL"
    else:
        raise ValueError  # "data_source"

    if data_type in ["ori", "1m"]:
        filename = options.datadir + "/" + station.upper() + extra + "_Minute.txt"
    elif data_type in ["1h"]:
        filename = options.datadir + "/" + station.upper() + extra + "_Hour.txt"
    else:
        print "unknown data:", data_type
    #if options.year or options.month:
    #    print "Warning: --year and --month are not used for reading Bartol data."

    from nmdb.station.bartol import read_txt
    data = read_txt(filename, data_type)  # TODO options
    if year is None:
        if month is not None or day is not None:
            raise ValueError  # if year is None, so should month and day
        value = data  # all available data
    else:  # year is given
        value = []
        if month is None:  # filter by year
            for row in data:
                thisdate = row[0].date()
                if thisdate.year == year:
                    value.append(row)
        else:
            if day is None:  # filter by month
                for row in data:
                    thisdate = row[0].date()
                    if thisdate.year == year and thisdate.month == month:
                        value.append(row)
            else:  # filter by day
                for row in data:
                    thisdate = row[0].date()
                    if thisdate.year == year and thisdate.month == month and thisdate.day == day:
                        value.append(row)
    return value


## --------------------------------------------------------------------------
def read_txt(filename, data_type):  # options?
    """format: yyyyy-mn-dom hh:mm:ss corr press uncorr"""
    #line = " "
    try:
        myfile = open(filename, "r")
        pos = myfile.tell()
        # skip the first line, if it documents the file format
        line = myfile.readline()
        if (30 < len(line) < 50):  # this looks like data, so scroll back
            myfile.seek(pos)

        data = []
        if data_type in ["1m", "ori", "rev"]:
            interval = 60  # calculate actual interval?
        elif data_type in["1h"]:
            interval = 3600  # hour data
        else:
            print "unknown data:", data_type
            sys.exit(1)

        while line:
            line = myfile.readline()

            ## longer line indicates description line
            if (30 < len(line) < 50):
                (year, month, day, hour, minute, second, dat) = \
                       parse_date(line)
                corr = float(dat.split()[0])
                # convert to mbar, round to two(!) digits after the decimal
                press = round(mbar(float(dat.split()[1])), 2)
                uncorr = float(dat.split()[2])

                uncorr = check_data(uncorr, cr_min=10., cr_max=10000.)
                press = check_pressure(press, p_min=600., p_max=1100.)
                corr = check_data(corr, cr_min=10., cr_max=10000.)
                ceff = corr

                data.append([  # order as in NMDB
                    datetime.datetime(year, month, day, hour, minute, second),
                    interval, uncorr, ceff, corr, press
                    ])

        return data

    except IOError:
        print "file %s not found" % (filename)
        sys.exit(1)


## --------------------------------------------------------------------------
def main():

    import optparse
    parser = optparse.OptionParser("usage: %prog [options]")
    parser.add_option("-v", dest="verbose", default=0, action="count",
            help="increment output verbosity; may be specified multiple times")
    (options, args) = parser.parse_args()

    print "This is the bartol module."
    options.datadir="/var/tmp/nmdb"

    station = "newk"
    station = "sopo"
    data_type="1h"
    data_type="1m"
    year = 2013
    month = 7
    day = 10
    month = 11
    day = 8

    data = read_rev(options, station, data_type, year, month, day)
    #data = read_rt(options, station, data_type, year, month, day)
    for line in data:
        print line

## --------------------------------------------------------------------------
if __name__ == '__main__':
    main()
